from django import http

from django.shortcuts import render

# Create your views here.
from django.views import View
from django.core.cache import cache

from apps.areas.models import Area


class SubAreasView(View):
    def get(self, request, parentid):

        sub_data = cache.get('sub_data_%s' % parentid)
        if sub_data:
            return http.JsonResponse({'code': 0, 'errmsg': 'OK', 'sub_data': sub_data})

        parent = Area.objects.get(id=parentid)
        sub_list = parent.subs.all()
        subs = []
        for i in sub_list:
            subs_model={
                'id':i.id,
                'name':i.name
            }
            subs.append(subs_model)

        sub_data = {
            'id':parent.id,
            'name':parent.name,
            'subs':subs
        }

        cache.set('sub_data_%s' % parentid, sub_data, 3600)

        return http.JsonResponse({'code':0, 'errmsg':'ok', 'sub_data':sub_data})



class ProvinceView(View):
    # 省级查询
    def get(self, request):

        # 缓存
        model_list = cache.get('province_list')
        if model_list:
            return http.JsonResponse({"code":0, "errmsg":"OK", "province_list": model_list})


        province_model_list = Area.objects.filter(parent=None)
        # 将查询集转换成字典列表
        model_list = []
        for i in province_model_list:
            province_model={
                'id':i.id,
                'name':i.name
            }
            model_list.append(province_model)

        cache.set('province_list', model_list, 3600)

        return http.JsonResponse({'code':0, 'errmsg':'ok', 'province_list':model_list})

